package com.sh;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;

/**
 * 自定义类加载器
 * 1.继承ClassLoader
 * 2.重写loadClass方法
 *   2.1 获取字节码
 *   2.2 name.startsWith("java.")时调用父类方法
 */

public class MyClassLoader extends ClassLoader {

    public MyClassLoader() {
    }

  @Override
  public Class<?> loadClass(String name) throws ClassNotFoundException {
      if ( name.startsWith("java.") ){
          return super.loadClass(name);
      }
      return findClass(name);
  }


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] bytes = loadClassData(name);
        return defineClass(name,bytes, 0, bytes.length);
    }

    // 模拟 URlClassLoader 加载class文件
    private byte[] loadClassData(String name) {
        String file1 = MyClassLoader.class.getResource("").getFile();
        name = name.substring(name.lastIndexOf(".") + 1)+".class";
        String name1 = file1 + File.separatorChar+name;
        File file = new File(name1);
        if (file.exists()) {
            try (
                    FileInputStream fis = new FileInputStream(file);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ) {
                byte[] buffer = new byte[1024];
                int size = 0;
                while ((size = fis.read(buffer)) != -1) {
                    baos.write(buffer, 0, size);
                }

                return baos.toByteArray();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            throw new RuntimeException("文件不存在");
        }
        return null;
    }

}
